<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\api\error\CodeBase;
use app\api\error\Common as CommonError;
use app\common\logic\UserNotice;
use app\common\model\GameCategory;
use app\common\model\Idcard;
use app\common\model\LoginLog;
use app\common\model\Member;
use app\common\model\PlatformPay;
use app\common\model\SweepCode;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserBlackRecord;
use app\common\model\UserEmailLog;
use app\common\model\UserLoginAddress;
use app\common\model\UserSms;
use \Firebase\JWT\JWT;
use think\Db;

/**
 * 接口基础逻辑
 */
class Common extends ApiBase
{

    /**
     * 登录接口逻辑
     */
//    public function login($data = [])
//    {
//
//        $result=mycurl(GAME_URL.'/ic/user/data?token='.$data['token']);
//        if(!$result){
//            return ajaxreturn(1, lang('服务器繁忙,请稍后再试'));
//        }
//        $res=json_decode($result,true);
//        if(!isset($res['data'])){
//            return ajaxreturn(1,$result);
//        }
//        if(!$res['data']){
//            return ajaxreturn(1,$res['msg']);
//        }
//
//
//
//        Db::startTrans();
//
//
//
//        try{
//            $member = $this->modelMember->field('cover_id,id,mobile,username,is_black,password,login_count,last_login_time,pin_password')->where(['user_id' => $res['data']['userId']])->lock(true)->find();
////            $member = $this->modelMember->field('cover_id,id,mobile,username,is_black,password,login_count,last_login_time,pin_password')->where(['user_id' => $uid])->lock(true)->find();
//            if (empty($member)) {
//
//                    $arr=[
//                        'username'=> preg_replace('# #','',$res['data']['userName']),
//                        'mobile'=>$res['data']['phoneNum'],
//                        'area'=>(int)$res['data']['areaCode'],
//                        'user_image'=>$res['data']['headImgUrl'],
//                        'weixin'=>$res['data']['unionId'],
//                        'user_id'=>$res['data']['userId'],
//                    ];
//                    if(!empty($data['superiorId'])){
//
//                        $referee_bean = Member::get(['user_id'=>$data['superiorId']]);
//                        if (empty($referee_bean)) {
//                            return ajaxreturn(1, lang('邀请人错误'));
//                        }
//                        $arr['leader_id']=$referee_bean['id'];
//
//                    }
//                    $id=$this->modelMember->setInfo($arr);
//                    if(!empty($referee_bean)){
//                        $path=$id.','.$referee_bean['path'];
//                        Member::update(['id'=>$id,'path'=>$path,'dai_level'=>$referee_bean['dai_level']+1,'team_id'=>$referee_bean['team_id'],'team_number'=>$referee_bean['team_number']]);
//                        if($referee_bean->ceng_member){
//                            $ceng_member=$referee_bean->ceng_member.','.$id;
//                        }else{
//                            $ceng_member=$id;
//                        }
//                        $referee_bean->ceng_member=$ceng_member;
//                        $referee_bean->save();
//                    }else{
//                        Member::update(['id'=>$id,'path'=>$id.',']);
//                    }
//                    $member=$this->modelMember->field('cover_id,id,mobile,username,login_count,last_login_time')->where(['id' => $id])->lock(true)->find();
//                    $token=$this->tokenSign($member);
//                    $member->login_count+=1;
//                    $member->login_count+=1;
//                    $member->last_login_time=TIME_NOW;
//                    $member->login_token=$token;
//                    $member->save();
//                    UserAccount::addWallet($member['id']);
//
//
//            }else{
//                $token=$this->tokenSign($member);
//                $member->username=$res['data']['userName'];
//                if(!empty($res['data']['unionId'])){
//                    $member->weixin=$res['data']['unionId'];
//                }
//                $member ->mobile=$res['data']['phoneNum'];
//                $member ->area=(int)$res['data']['areaCode'];
//                $member->user_image=$res['data']['headImgUrl'];
//                $member->login_count+=1;
//                $member->last_login_time=TIME_NOW;
//                $member->login_token=$token;
//                $member->save();
//            }
//
//            Db::commit();
//        }catch ( \Exception $e){
//            Db::rollback();
//            return ajaxreturn(1, $e->getMessage());
//            return ajaxreturn(1, lang('服务器繁忙,请稍后再试'));
//        }
//        return ['user_token'=>$token];
//
//    }
    /**
     * 登录接口逻辑
     */
    public function login($data = [])
    {



        empty($data['mobile_type']) && $data['mobile_type']='';
        Db::startTrans();

        if($data['type']==1){
            $type=1;
            $member = $this->modelMember->field('cover_id,id,mobile,username,is_black,reg_ip,password,login_count,uuid,last_login_time,pin_password,is_black,no_login_time,is_login,area')->where(['username' => $data['username']])->lock(true)->find();
            if (empty($member)) {
                return ajaxreturn(1, lang('用户未注册'));
            }
            if ($member['is_black'] == 1) {
                $balck_log=UserBlackRecord::where(['user_id'=>$member['id'],'type'=>1])->order('id desc')->column('remark');
                return ajaxreturn(1,$balck_log);
            }
            if ($member['is_login'] == 0) {
                return ajaxreturn(1, lang('您的账户多次输入密码错误已被禁止登录，请知悉,解封时间为').date('Y-m-d H:i:s',$member['no_login_time']));
            }
            if (data_md5_key($data['password']) !== $member['password']) {
                $userinfo=cache($member['username'].$member['id']);

                if($userinfo){
                    if($userinfo['error_count'] >=2){

                        UserBlackRecord::create([
                            'user_id'=>$member['id'],
                            'create_time'=>TIME_NOW,
                            'type'=>3,
                            'remark'=>'多次输入密码错误被禁止登录'
                        ]);
                        $member->is_login=0;
                        $member->no_login_time=time()+getConfig('login_time')*3600;
                        $member->save();

                        $lang=in_array($member['area'],['86','852','853','886'])?'zh-hk':'en-us';
                        $content=getConfig('pwd_error_login_'.$lang);
                        $data = [
                            'mobile' => $member['mobile'],
                            'content' => $content,
                            'create_time' => TIME_NOW,
                            'sms_type' => 6,
                            'type' => 0,
                            'area'=>$member['area']
                        ];
                        $sms=UserSms::create($data);



                        if(getConfig('sms_is_test')!=1){
                            $state=send_sms($member['mobile'],$content ,config('settings'),$member['area']);
                            if($state){
                                UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                            }
                        }

                        Db::commit();
                        return ajaxreturn(1, lang('您的账户操作多次密码验证不正确，如果不是您本人操作，请前往修改密码'));
                    }else{
                        $userinfo['error_count'] +=1;
                        cache($member['username'].$member['id'],$userinfo,86400);
                    }
                }else{
                    $userinfo=['error_count'=>1,'create_time'=>time()];
                    cache($member['username'].$member['id'],$userinfo,86400);
                }
                if( $userinfo['error_count']>=3){
                    return ajaxreturn(1, lang('由于您的密码输入错误超过3次。已被锁定30分钟，请在30分钟后再次登录'));
                }else{
                    return ajaxreturn(1, lang('您的密码输入错误，请重新核对您的登录密码，本次累计输入错误 '.$userinfo['error_count'].lang('次')));
                }



            }
            cache($member['username'].$member['id'],null);
        }else{
            $type=2;
            $member = $this->modelMember->field('cover_id,reg_ip,area,id,mobile,username,is_black,password,login_count,last_login_time,uuid,pin_password')->where(['area' => $data['area'],'mobile'=>$data['mobile']])->lock(true)->find();
            if (empty($member)) {
                return ajaxreturn(1, lang('用户未注册'));
            }
           if(!$this->check_mobile_code($data)){

                return ajaxreturn(1, lang('验证码错误'));

           }

        }

        if ($member['is_black'] == 1) {
            $balck_log=UserBlackRecord::where(['user_id'=>$member['id'],'type'=>1])->order('id desc')->column('remark');
            return ajaxreturn(1,$balck_log);
        }




        $token=$this->tokenSign($member);

        try{
            $member->login_count+=1;
            $member->last_login_time=TIME_NOW;
            $member->login_token=$token;
            if(!$member['uuid']){
                if(empty($data['uuid'])){
                    return ajaxreturn(1,'您的账户当前未能获取到设备号，不能为您提供账户登陆服务，请您遵守Ccie的用户注册法则');
                }
                $member->uuid=$data['uuid'];
            }
            if(!$member['reg_ip']){

                $member->reg_ip=get_client_ip();
            }

            $ipinfo=get_ip_info(get_client_ip());
            $member->last_login_ip=get_client_ip();
            $member->mobile_type=$data['mobile_type'];
            $mobile_brand=mobile_type();
            $member->mobile_brand=$mobile_brand;
            if($ipinfo ){

                $member->last_login_area=$ipinfo['country'].$ipinfo['region'].$ipinfo['city'];
                //写入登录记录
                LoginLog::create([
                    'user_id'=>$member['id'],
                    'username'=>$member['username'],
                    'create_time'=>TIME_NOW,
                    'type'=>$type,
                    'ip'=>$_SERVER['REMOTE_ADDR'],
                    'location'=>$ipinfo['country'].$ipinfo['region'].$ipinfo['city'],
                    'network_operator'=>$ipinfo['isp'],
                    'mobile_type'=>$data['mobile_type'],
                    'mobile_brand'=>$mobile_brand,

                ]);
                if($ipinfo['country']=='中国'  ){
                    if($ipinfo['region']=='台湾省'  || $ipinfo['region']=='香港特别行政区'  || $ipinfo['region']=='澳门特别行政区'){
                        $member->country=$ipinfo['region'];
                    }else{
                        $member->country=$ipinfo['country'];
                    }

                }else{
                    $member->country=$ipinfo['country'];
                }

                //写入登录地址表
                $address_ifno=UserLoginAddress::get(['city'=>$ipinfo['city'],'user_id'=>$member['id']]);
                if($address_ifno){
                    $address_ifno->count+=1;
                    $address_ifno->save();
                }else{
                    UserLoginAddress::create([
                        'user_id'=>$member['id'],
                        'city'=>$ipinfo['city'],
                        'country'=>$ipinfo['country'],
                        'province'=>$ipinfo['region']
                    ]);
                }
                if($member['always_address'] &&  $member['always_address']!=$ipinfo['city'] ){
                    //异地区登录

                    $code=$ipinfo['region'];
                    $code1=$ipinfo['city'];

                    $lang=in_array($member['area'],['86','852','853','886'])?'zh-hk':'en-us';
                    $content=getConfig('remote_area_login_'.$lang);
                    $content=str_replace('{$code}', $code, $content);
                    $content=str_replace('{$code1}', $code1, $content);
                    $data = [
                        'mobile' => $member['mobile'],
                        'content' => $content,
                        'create_time' => TIME_NOW,
                        'sms_type' => 4,
                        'type' => 0,
                        'area'=>$member['area']
                    ];
                    $sms=UserSms::create($data);

                    if(getConfig('sms_is_test')!=1){
                        $state=send_sms($member['mobile'],$content ,config('settings'),$member['area']);
                        if($state){
                            UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                        }
                    }
                }

            }else{
                //写入登录记录
                LoginLog::create([
                    'user_id'=>$member['id'],
                    'username'=>$member['username'],
                    'create_time'=>TIME_NOW,
                    'type'=>$type,
                    'ip'=>$_SERVER['REMOTE_ADDR']
                ]);
            }
            !empty($data['uuid']) && $member->login_uuid=$data['uuid'];
            $member->save();
            //写入登录缓存
//            cache('login'.$member['id'],1,1800);
            Db::commit();
        }catch ( \Exception $e){
            Db::rollback();
            return ajaxreturn(1, $e->getMessage());
            return ajaxreturn(1, lang('服务器繁忙,请稍后再试'));
        }

        return ['user_token'=>$token];

    }
    /**
     *获取公告
     */
    public function get_notice($data)
    {

        $where=['status'=>1];
        !empty($data['cate_id'])  && $where['cate_id']=$data['cate_id'];
        $notice=\app\common\model\Notice::field('id,title,content,is_push,create_time')->where($where)->order('create_time desc')->select();
        $time=time();
        foreach ($notice as $k=>$v){

            $minute=floor(($time-$v->data['create_time'])/60);
            $hour=floor($minute/60);
            $day=floor($hour/24);
            $month=floor($day/30);
            if(floor(($time-$v->data['create_time']))<1){
                $notice[$k]['time']=floor(($time-$v->data['create_time'])).lang('秒前');
            }elseif($minute<60){
                $notice[$k]['time']=$minute.lang('分钟前');

            }elseif($hour<24){
                $notice[$k]['time']=$day.lang('小时前');

            }elseif($day<30){
                $notice[$k]['time']=$day.lang('天前');
            }else{

                $notice[$k]['time']=$month.lang('月前');
            }

        }
         return  $notice;
    }


    /**
     *获取公告
     */
    public function get_notice_info($data)
    {

        $info=\app\common\model\Notice::get($data['id']);
        return  $info;
    }


    /**
     * 绑定手机
     */
    public function blind_mobile($data){
        if(!$this->check_mobile_code($data)){

            return ajaxreturn(1, lang('验证码错误'));

        }

//        if (!match_mobile($data['mobile'])) {
//            return ajaxreturn(1, lang('手机号码格式不正确'));
//        }
        $uid=decoded_user_token($data['user_token'],'member_id');
        if($this->modelMember->getInfo(['mobile'=>$data['mobile'],'area'=>$data['area']])){
            return ajaxreturn(1, lang('手机已注册'));
        }
        $this->modelMember->setInfo(['mobile'=>$data['mobile'],'area'=>$data['area']],['id'=>$uid]);
        return ajaxreturn(0, lang('绑定成功'));
    }

    /**
     * 发送短信
     */
    public function send_sms($data)
    {

        $mobile = $data['mobile'];
        $area = empty($data['area'])?86:$data['area'];
        if (empty($mobile)) {
            return ajaxreturn(1, lang('手机号码不能为空'));
        }
//        if (empty($data['ticket'])) {
//            return ajaxreturn(1, lang('验证错误'));
//        }
//        if (empty($data['randstr'])) {
//            return ajaxreturn(1, lang('验证错误'));
//        }
//        if (!qq_captcha($data['ticket'],$data['randstr'])) {
//            return ajaxreturn(1, lang('验证错误'));
//
//        }

        if($data['type']==1){
            //注册验证码
            if($member=Member::get(['mobile'=>$data['mobile'],'area'=>$data['area']])){
                return ajaxreturn(1, lang('手机已注册'));
            }

        }
        if($data['type']==2){
            //忘记密码验证码
            if(!$member=Member::field('cover_id,id,mobile,username')->where(['mobile'=>$data['mobile'],'area'=>$data['area']])->find()){
                return ajaxreturn(1, lang('手机未注册'));
            }

        }
      	if($data['type']==3){
            //绑定手机号
            if(!$member=Member::field('cover_id,id,mobile,username')->where(['username'=>$data['username']])->find()){
                return ajaxreturn(1, lang('账户不存在'));
            }

        }
      	if(UserSms::where(['mobile'=>$mobile,'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->count()>=10){
            return ajaxreturn(1, lang('您今天短信发送条数已达到10条上限，无法再为您提供短信发送'));
        }

        if($code_count=UserSms::where(['mobile'=>$mobile,'type'=>$data['type'],'sms_type'=>$data['sms_type'],'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->count()>=3){
            if($codeinfo=UserSms::where(['mobile'=>$mobile,'type'=>$data['type'],'sms_type'=>$data['sms_type']])->order('id desc')->find()){
                if($codeinfo['create_time']+300>TIME_NOW){
                    return ajaxreturn(1, lang('由于您发送验证码太过频繁,五分钟后再试'));
                }

            }
        }

        if(getConfig('sms_is_test')==1){
            $code = '000000';
        }else{
            $code = create_rand_number(4);
        }
        $lang=in_array($area,['86','852','853','886'])?'zh-hk':'en-us';
        switch ($data['sms_type']){
            case  1:
            case  13:
            case  14:
                //注册
                $content=getConfig('code_sms_'.$lang);
                $content=str_replace('{$code}', $code, $content);
                break;
            case  9:
               //修改密码
                $content=getConfig('up_pwd_'.$lang);
                $content=str_replace('{$code}', $code, $content);
                break;
            case  10:
                //修改支付密码密码
                $content=getConfig('up_pin_pwd_'.$lang);
                $content=str_replace('{$code}', $code, $content);
                break;
            case  11:
                //修改手机
                $code1=$member['username'];
                $content=getConfig('up_mobile_'.$lang);
                $content=str_replace('{$code}', $code, $content);
                $content=str_replace('{$code1}', $code1, $content);
                break;
            case  12:
                //手机登录
                $content=getConfig('mobile_login_'.$lang);
                $content=str_replace('{$code}', $code, $content);
                break;
            case  16:
                //总包提现
                $content=getConfig('balance_withdrwal_'.$lang);
                $content=str_replace('{$code}', $code, $content);
                break;


        }
        $token = md5(md5(create_rand_number(64)) . create_rand_number(64));
//        $content = lang('您本次的验证码是') . $code . ','.lang('若非本人操作请忽略此消息');

        $data = [
            'mobile' => $mobile,
            'code' => $code,
            'content' => $content,
            'create_time' => TIME_NOW,
            'sms_type'=>$data['sms_type'],
            'token' => $token,
            'type' => $data['type'],
            'area'=>$area
        ];


        $sms=UserSms::create($data);
        if(getConfig('sms_is_test')!=1){
            $result=send_sms($mobile,$content ,config('settings'),$area);
            if($result){
                UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                return ['code'=>0,'msg'=>lang('发送成功'),'dat'=>$token];
            }else{

                return ['code'=>1,'msg'=>lang('发送失败')];
            }
        }else{
            return ['code'=>0,'msg'=>lang('发送成功'),'dat'=>$token];

        }



    }


    /**
     * 发送邮箱
     */
    public function send_email($data)
    {

        $mobile = $data['user_email'];

        if (empty($mobile)) {
            return ajaxreturn(1, lang('邮箱不能为空'));
        }
        if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$data['user_email'])){
            return ajaxreturn(1, lang('邮箱格式错误'));
        }
        if (empty($data['ticket'])) {
            return ajaxreturn(1, lang('验证错误'));
        }
        if (empty($data['randstr'])) {
            return ajaxreturn(1, lang('验证错误'));
        }
        if (!qq_captcha($data['ticket'],$data['randstr'])) {
            return ajaxreturn(1, lang('验证错误'));

        }


        if($code_count=UserEmailLog::where(['email'=>$mobile,'type'=>$data['type'],'create_time'=>['between',[getTodayStart(),getTodayEnd()]]])->count()>=3){
            if($codeinfo=UserEmailLog::where(['email'=>$mobile,'type'=>$data['type']])->order('id desc')->find()){
                if($codeinfo['create_time']+300>TIME_NOW){
                    return ajaxreturn(1, lang('由于您发送验证码太过频繁,五分钟后再试'));
                }

            }
        }

        if(getConfig('email_is_test')==1){
            $code = '000000';
        }else{
            $code = create_rand_number(4);
        }

        switch ($data['type']){
            case  1:
                $msg='绑定邮箱';
                break;
            case  2:
                $msg='提现';
                break;
            case  3:
                $msg='绑定收款方式';
                break;
            case  4:
                $msg='修改收款方式';
                break;
            case  5:
                $msg='修改交易密码';
                break;
            case  6:
                $msg='修改密码';
                break;
            case  7:
                $msg='找回密码';
                break;
            case  8:
                $msg='修改邮箱';
                break;
            case  9:
                $msg='提币';
                break;
            case  10:
                $msg='扫码支付';
                break;
            default:
                $msg='';
                break;


        }
        $token = md5(md5(create_rand_number(64)) . create_rand_number(64));
//        $content = lang('您本次的验证码是') . $code . ','.lang('若非本人操作请忽略此消息');

        $data = [
            'email' => $mobile,
            'code' => $code,
            'create_time' => TIME_NOW,
            'token' => $token,
            'type' => $data['type'],
        ];

        $arr['code']=$code;
        $arr['action']=$msg;
        $sms=UserEmailLog::create($data);
        if(getConfig('email_is_test')!=1){
            $result=send_submall($mobile ,$arr);
            if($result['status']=='success'){
                UserEmailLog::where(['id'=>$sms->id])->update(['state'=>2,'send_id'=>$result['return'][0]['send_id']]);
                return ['code'=>0,'msg'=>lang('发送成功'),'dat'=>$token];
            }else{

                return ['code'=>1,'msg'=>lang('发送失败')];
            }
        }else{
            return ['code'=>0,'msg'=>lang('如"收件箱"未收到验证码，请前往邮箱中的"垃圾箱"查看'),'dat'=>$token];

        }



    }


    /**
     * 注册方法
     */
    public function register($data)
    {

        if (config('settings')['user_base_reg_is_open'] != 1) {
            return ajaxreturn(1, lang('暂未开启注册功能'));
        }

        if (empty($data['username'])) {
            return ajaxreturn(1, lang('用户名或密码不能为空'));
        }
        if(preg_match('/[\x{4e00}-\x{9fa5}]+/u',$data['username'])){
            return ajaxreturn(1, lang('用户名不能有中文'));
        }
        if (strlen($data['username'])<3)
        {
            return ajaxreturn(1, lang('用户名至少3位起'));
        }

        if(!preg_match("/^[a-z\d]*$/i",$data['username']))
        {
            return ajaxreturn(1, lang('用户名必须包含数字和字母'));
        }
        if(replaceSpecialChar($data['username'])){
            return ajaxreturn(1, lang('用户名不能有特殊字符或者空格'));
        }
        if (strlen( $data['password']) < 6) {
            return ajaxreturn(1, lang('登录密码不能小于6位'));
        }
        if ( $data['password'] == '123456') {
            return ajaxreturn(1, lang('您的登录密码设置的太过简单，请不要使用123456作为登录密码'));
        }
//        if (strlen($data['pin_password']) != 6) {
//            return ajaxreturn(0, lang('PIN密码不能小于6位'));
//        }
//        if ( $data['pin_password'] == '123456') {
//            return ajaxreturn(1, lang('您设置的交易密码太过简单'));
//        }
//        if (!preg_match('/^[0-9]*[1-9][0-9]*$/' ,$data['pin_password'])) {
//            return ajaxreturn(0, lang('二级密码必须是数字'));
//        }
        if (empty($data['ticket'])) {
            return ajaxreturn(1, lang('验证错误'));
        }
        if (empty($data['randstr'])) {
            return ajaxreturn(1, lang('验证错误'));
        }
        if (!qq_captcha($data['ticket'],$data['randstr'])) {
            return ajaxreturn(1, lang('验证错误'));

        }

        if (empty($data['invite_code'])) {
            return ajaxreturn(1, lang('邀请人错误'));
        }

        $referee_bean = Member::where(['invite_code|username|mobile'=>$data['invite_code']])->lock(true)->find();
        if (empty($referee_bean)) {
            return ajaxreturn(1, lang('邀请人错误'));
        }
//        if(!$this->check_mobile_code($data)){
//
//            return ajaxreturn(1, lang('验证码错误'));
//
//        }
        $data['invite_code']=$this->degui();
        $data['leader_id']=$referee_bean['id'];
//        $data['pin_password']= md5($data['pin_password'].'pin');


        Db::startTrans();
        $user = Member::where(['username'=>$data['username']])->find();
        if (!empty($user)) {
            return ajaxreturn(1, lang('用户名已存在，请更换'));
        }
//        $user = Member::where(['mobile'=>$data['mobile']])->find();
//        if (!empty($user)) {
//            return ajaxreturn(1, lang('手机号已注册，请更换'));
//        }

//        if(empty($data['uuid'])){
//            return ajaxreturn(1,'您的账户当前未能获取到设备号，不能为您提供账户登陆服务，请您遵守Ccie的用户注册法则');
//        }

        try{
            $data['reg_ip']=get_client_ip();
            $result = $this->modelMember->setInfo($data);

            //创建账户
            UserAccount::addWallet($result);
            $member=$this->modelMember->getInfo(['id'=>$result]);


            //写入邀请人层级
            if($referee_bean['ceng_member']){
                $referee_bean->ceng_member=$result.','.$referee_bean['ceng_member'];

            }else{
                $referee_bean->ceng_member=$result;
            }
            $member->path=$result.','. $referee_bean->path;
            $member->game_point_money=$referee_bean->game_point_money-2;
            $member->dai_level=$referee_bean->dai_level+1;
            $member->team_id=$referee_bean['team_id'];
            $member->team_number=$referee_bean['team_number'];

            $member->save();
            $referee_bean->save();

            //消息推送
            $path=rtrim( $referee_bean->path,',');
            $path=explode(',',$path);
            $reg_type=empty($data['reg_type'])?'APP':'二维码扫码';
            $notices=[];
            $ipinfo=get_ip_info(get_client_ip());
            $city=$ipinfo?$ipinfo['city']:'';
            foreach ($path as $k =>$v){
                $notice=[
                    'user_id'=>$v,
                    'create_time'=>TIME_NOW,
                    'type'=>1,
                ];
               if($k==0){
                   $notice['title']='您有新增下级成员'.$data['username'].'，来源于通过'.$reg_type.'方式注册成功' ;
               }else{

                   $notice['title']='您有新团队成员'.$data['username'].'（第'.($k).'代）加入，通过'.$reg_type.'方式注册成功。' ;
               }


                $json_arr=[
                    'username'=>$data['username'],
                    'leader_name'=>$referee_bean->username,
                    'reg_time'=>date('Y-m-d H:i:s'),
                    'reg_type'=>$reg_type,
                    'reg_city'=>$city
                ];
                $notice['json_msg']=json_encode($json_arr);
                $notices[]=$notice;
            }
            \app\common\model\UserNotice::insertall($notices);
            $paths=Member::where(['id'=>['in',explode(',',$member->path)],'level_id'=>['gt',1]])->column('id');
            //团队升级
            $member->upgrade_level($paths);
            Db::commit();
            return ajaxreturn(0,lang('注册成功'));
        }catch ( \Exception $e){
            return ajaxreturn(1, $e->getMessage());
            Db::rollback();
            return ajaxreturn(1, lang('服务器繁忙,请稍后再试'));
        }
    }


    
    /**
     * JWT验签方法
     */
    public static function tokenSign($member)
    {
        
        $key = API_KEY . JWT_KEY;
        
        $jwt_data = ['member_id' => $member['id'], 'create_time' => $member['create_time']];
        
        $token = [
            "iss"   => "HaoMen JWT",         // 签发者
            "iat"   => TIME_NOW,              // 签发时间
            "exp"   => TIME_NOW + TIME_NOW,   // 过期时间
            "aud"   => 'HaoMen',             // 接收方
            "sub"   => 'HaoMen',             // 面向的用户
            "data"  => $jwt_data
        ];
        
        $jwt = JWT::encode($token, $key);

        
        return $jwt;
    }
    
    /**
     * 退出登录
     */
    public function loginout($data)
    {
        
        //$member = get_member_by_token($data['user_token']);
        $uid=$this->logicApiBase->member['id'];
        $member_info = $this->logicMember->getMemberInfo(['id' => $uid]);
        $member_info->login_token='';
        $member_info->save();

        
        return ajaxreturn(0,lang('退出成功'));
    }

//    /**
//     * 修改密码
//     */
//    public function changePassword($data)
//    {
//
//        $member = get_member_by_token($data['user_token']);
//
//        $member_info = $this->logicMember->getMemberInfo(['id' => $member->member_id]);
//
//        if (empty($data['old_password']) || empty($data['new_password'])) {
//
//            return ajaxreturn(1, lang('旧密码或新密码不能为空'));
//        }
//
//        if (data_md5_key($data['old_password']) !== $member_info['password']) {
//
//            return ajaxreturn(1, lang('登录密码错误'));
//        }
//
//        $member_info['password'] = $data['new_password'];
//
//          $this->logicMember->setInfo($member_info);
//
//        return ajaxreturn(0,lang('修改成功'));
//    }
    /**
     * 修改密码
     */
    public function changePassword($data)
    {



        $member_info =$this->logicApiBase->member;
        if (empty($data['password'])) {

            return ajaxreturn(1, lang('新密码不能为空'));
        }

        if($data['type']==1 && !$member_info['pin_password']){

        }else{
            if(!empty($data['email_type'])){
                $user_sms_bean = $this->modelUserEmailLog->where(array('token' => $data['token'], 'email' => $data['mobile'],'code'=>$data['code'], 'status' => 0))->find();
                if (empty($user_sms_bean)) {
                    return ajaxreturn(1, lang('验证码错误'));

                }
            }else{
                $res=$this->check_mobile_code($data);
                if(!$res){
                    return ajaxreturn(1, lang('验证码错误'));
                }
            }

        }
        if ($data['password']!=$data['confirm_password']) {

            return ajaxreturn(1, lang('两次密码不一致'));
        }
        if($data['type']==1){
            $arr['pin_password']=md5($data['password'].'pin');

            unset($data['password']);
        }else{
            $arr['password']=data_md5_key($data['password']);
            $arr['up_pwd_time']=TIME_NOW;

        }
        Member::where(['id'=>$member_info['id']])->update($arr);
        if($data['type']!=1){
            return ajaxreturn(0,lang('您的登录密码已修改成功，请牢记您的登录密码，并重新登录验证'));
        }else{
            return ajaxreturn(0,lang('修改成功'));
        }

    }

    /***
     * 忘记密码
     */
    public function forget_pwd($data){
        if (empty($data['mobile'])) {
            return ajaxreturn(1, lang('手机号码不能为空'));
        }
        if(empty($data['email_type'])){
            if (empty($data['area'])) {
                return ajaxreturn(1, lang('请选择区号'));
            }
            $member_info = $this->modelMember->getInfo(['mobile' =>$data['mobile'],'area'=>$data['area']]);
        }else{
            $member_info = $this->modelMember->getInfo(['user_email' =>$data['mobile']]);
        }


        if(!$member_info){
            return ajaxreturn(1, lang('用户未注册'));
        }
        if (empty($data['code'])) {
            return ajaxreturn(1, lang('验证码不能为空'));
        }
        if (empty($data['password'])) {
            return ajaxreturn(1, lang('密码不能为空'));
        }
        if ($data['password']!=$data['reset_password']) {
            return ajaxreturn(1, lang('两次密码不一致'));
        }
        if(!empty($data['email_type'])){
            $user_sms_bean = $this->modelUserEmailLog->where(array('token' => $data['token'], 'email' => $data['mobile'],'code'=>$data['code'], 'status' => 0))->find();
            if (empty($user_sms_bean)) {
                return ajaxreturn(1, lang('验证码错误'));

            }
            $data['user_email']=$data['mobile'];
            unset($data['mobile']);
        }else{
            $user_sms_bean = $this->modelUserSms->where(array('token' => $data['token'], 'mobile' => $data['mobile'], 'status' => 0, 'code' => $data['code']))->find();
            if (empty($user_sms_bean)) {
                return ajaxreturn(1, lang('验证码错误'));

            }
        }


        $data['id'] = $member_info['id'];
        $this->modelMember->setInfo($data);
        return ajaxreturn(0,lang('您的登录密码已修改成功，请牢记您的登录密码，并重新登录验证'));

    }
    
    /**
     * 友情链接
     */
    public function getBlogrollList()
    {
        
        return $this->modelBlogroll->getList([DATA_STATUS_NAME => DATA_NORMAL], true, 'sort desc,id asc', false);
    }
    /**
     * banner
     */
    public function getBanner($data)
    {
        $this->modelBanner->limit=3;
        $list= $this->modelBanner->getList(['cate_id' => $data['type']], true, 'sort desc,id asc', false);
        foreach ( $list as $k=>$v){
            $list[$k]['image']=$v->image;
        }
        return $list;
    }

    public function  check_idcard($data){
        $member=$this->logicApiBase->member;
        if(strlen($data['idcard'])!=15 && strlen($data['idcard'])!=18 ){
            return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
        }
//        if(getConfig('idcard_switch')==1){
            if(!is_idcard($data['idcard'])){
                return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
            }

            if (!checkName($data['true_name'])) {
                return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
            }
            $idcard_info=Idcard::get(['idCard'=>$data['idcard']]);
            if($idcard_info){
                if($idcard_info['name']!=$data['true_name']){
                    return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
                }

            }else{
                $count=cache('idcard'.$member['id'])+0;
                if($count>3){
                    return ajaxreturn(1,lang('身份证姓名错误过多'));
                }
                if(getConfig('idcard_switch')==1){
                    $idcard_getinfo=check_card($data['idcard'],$data['true_name']);
                    if($idcard_getinfo){
                        if($idcard_getinfo['status']=="01"){
                            unset($idcard_getinfo['status']);
                            unset($idcard_getinfo['msg']);
                            unset($idcard_getinfo['prefecture']);

                            $idcard_getinfo['sex']=='男'?$idcard_getinfo['sex']=1:$idcard_getinfo['sex']=2;
                            Idcard::create($idcard_getinfo);
                        }else{

                            cache('idcard'.$member['id'],$count+1,86400);
                            return ajaxreturn(1,lang('经过第三方验证您输入的姓名和身份证不符合，请重新修改名字或身份证号码'));
                        }
                    }else{
                        return ajaxreturn(1,lang('身份证验证失败'));
                    }
                }

            }
//        }
    }




    /**
     * banner
     */
    public function get_currency_pay()
    {

        $list= $this->modelWalletRechargeType->getList([], 'id,cover_id,address,currency_id', 'id asc', false);
        foreach ( $list as $k=>$v){
            $list[$k]['currency_name']=$v->currency_name;
            $list[$k]['image']=$v->image;
        }

        return $list;
    }

    /**
     * banner
     */
    public function get_game_list()
    {

        $list= $this->modelGame->getList([], 'id,name,cover_id,conversion_available,conversion_shandui', 'id asc', false);
        foreach ( $list as $k=>$v){
            $list[$k]['image']=$v->image;
        }
        return $list;
    }


    /**
     * 根据分类获取游戏列表
     */
    public function get_cate_game($data)
    {
        if(!empty($data['id'])){
            $where['category_id']=$data['id'];
        }else{
            $where['is_index']=1;
        }
        $list= $this->modelGame->getList($where, 'id,name,cover_id,intro', 'id asc', false);
        foreach ( $list as $k=>$v){
            $list[$k]['image']=$v->image;
        }
        return $list;
    }


    /**
     * banner
     */
    public function game_detail($data)
    {

        $info= $this->modelGame->getInfo(['id'=>$data['id']], 'id,name,intro,cover_id,url,content,img_ids,is_hot,is_top,top_cover_id', 'id asc', false);

        $info['image']=$info->image;
        $info['top_image']=$info->top_image;
        $image_array=[];
        if( $info['img_ids']){
            $img_ids_array = str2arr($info['img_ids']);
            foreach ($img_ids_array as $k=>$v){
                $image_array[]=get_picture_url($v,false);
            }
        }

        $info['image_array']=$image_array;
        return $info;
    }
    /**
     * 应用分类
     */
    public function game_cate()
    {

        $list= $this->modelGameCategory->getList(['status'=>1], 'id,name,cover_id', 'id asc', false);
        foreach ( $list as $k=>$v){
            $list[$k]['image']=$v->image;
        }
        return $list;
    }
    /**
     * 推广海报列表
     */
    public function poster_list()
    {

        $list= $this->modelPosterPicture->getList(['status'=>1], 'id,cover_id', 'id asc', false);
        foreach ( $list as $k=>$v){
            $list[$k]['image']=$v->image;
        }
        return $list;
    }
    /**
     * 功能介绍
     */
    public function get_version_list()
    {
        $list= $this->modelArticle->getList(['category_id'=>13], 'id,name,create_time', 'id desc', false);
//        $list= $this->modelVersion->getList(['is_enable'=>1], 'id,title,create_time', 'id asc', false);
        return $list;
    }

    /**
     * 功能介绍
     */
    public function get_version_info($data)
    {

        $info= $this->modelVersion->getInfo(['id'=>$data['id'],'is_enable'=>1], 'id,title,content,download_url_ios,download_url,create_time');
        return $info;
    }

    /**
     * 最新app版本
     */
    public function get_newest_version()
    {

        $info= $this->modelVersion->field( 'id,title,content,version,download_url_ios,start_time,end_time,download_url,create_time')->where(['is_enable'=>1,'status'=>1])->order('version desc')->find();
        !empty($info['start_time'])  && $info['start_time']=date('Y-m-d H:i:s',$info['start_time']);
        !empty($info['end_time'])  && $info['end_time']=date('Y-m-d H:i:s',$info['end_time']);
        return $info;
    }

    /**
     * 关于我们
     */
    public function get_about()
    {
        if(cache('about')){

            return cache('about');
        }else{
          $about=  $this->modelSysConfig->where('parent_id',7)->column('code,value');
          $about['about_logo']=get_picture_url($about['about_logo'],false);
            cache('about',$about);

        }
        return cache('about');

    }
  
  	 /**
     * 第三方平台跳转接口
     */
    public function check_game($data)
    {
        $uid=decoded_user_token($data['user_token'],'member_id');
        if(!$game=$this->modelGame->getInfo(['id'=>$data['game']])){
            return ['url'=>'','status'=>1];
        }
        if($game['state']==0){
            return ['url'=>'','status'=>1];
        }
        if($game['url']==''){
            return ['url'=>'','status'=>1];
        }
        $member=$this->modelMember->getInfo(['id'=>$uid]);
        $username=$member['username'];
        $url=$game['url'].'?account='.$username.'&authkey='.data_md5_key($username).'&token=b1435fd198da820cf278186c0c8bdf5e';
        return ['url'=>$url,'status'=>0];
    }

    /**
     * 闪兑换算接口
     */
    public function get_conversion($data)
    {
        if(!$wallet=\app\common\model\Wallet::get([$data['wallet_id']])){
            return ajaxreturn(1,lang('币种错误'));
        }
        if($wallet['is_currency']!=1 && $wallet['is_virtual']!=2){
            return ajaxreturn(1,lang('币种错误'));
        }
        $flash_wallet=\app\common\model\Wallet::get(2);
        if($data['type']==1){
            //闪兑换算区块链
            $number=$data['number']*$flash_wallet['parities']/$wallet['parities'];
            $number=sprintf("%.8f",$number);
        }else{
            //区块链换算区块链
            $number=$data['number']*$wallet['parities']/$flash_wallet['parities'];
            $number=sprintf("%.2f",$number);
        }
        return ['number'=>$number];

    }


    /**
     * 扫码加糖果
     */
    public function sweep_code($data)
    {

        if(empty($data['invite_code'])){
            return ajaxreturn(1,lang('邀请码不能为空'));
        }


        Db::startTrans();
        $user=$this->modelMember->where(['invite_code'=>$data['invite_code']])->lock(true)->find();
        if(!$user){
            return ajaxreturn(1,lang('邀请码错误'));
        }
        $data['login_ip']=get_client_ip();
        try{

            //写入扫码表
            if(!SweepCode::get(['user_id'=>$user['id'], 'login_ip'=>$data['login_ip']])){
                SweepCode::create([
                    'user_id'=>$user['id'],
                    'login_ip'=> $data['login_ip']
                ]);
                //改变用户积分余额
                $user->paw_account+=1;
                $user->save();
                Db::commit();
            }else{
                return ajaxreturn(1,lang('已经扫过,不能重复获得糖果'));
            }

            return ajaxreturn(0,lang('扫码成功'));


        }catch (\Exception $e){

            Db::rollback();
//            return ajaxreturn(0,$e->getmessage());
            return ajaxreturn(1,lang('系统繁忙,请稍后再试'));
        }

    }
  
    // 第三方平台同步用户逻辑
    public function get_user_list($data)
    {
       if(empty($data['time2']) || empty($data['time2'] )){
           return ajaxreturn(1, lang('时间错误'));
        }
        $where['create_time']=['between',[strtotime($data['time1']),strtotime($data['time2'])]];
        $where['is_inside']=0;
       $where['status']=1;
        $list=\app\common\model\Member::field('id,create_time,username,mobile,leader_id')->where($where)->order('id asc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['add_time']=date('Y-m-d H:i:s',$v->create_time);
            $list[$k]['leader_name']=$v->mem?$v->mem->username:'';
            unset($v->mem);
            unset($v->create_time);
            unset($v->leader_id);
        }

        return $list;

    }


    // 第三方平台同步充值逻辑
    public function get_recharge_list($data)
    {
      	if(empty($data['time2']) || empty($data['time2'] )){
           return ajaxreturn(1, lang('时间错误'));
        }
       	$where['create_time']=['between',[strtotime($data['time1']),strtotime($data['time2'])]];
        $where['status']=1;
        $where['state']=1;
        $where['type']=4;
        $list=\app\common\model\Transfer::field('id,create_time,user_id,number,form_wallet_id')->where($where)->order('create_time asc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['add_time']=date('Y-m-d H:i:s',$v->create_time);
            $list[$k]['username']=$v->member->username;
            $list[$k]['wallet_name']=$v->wallet['name'];
            unset($v->create_time);
            unset($v['user_id']);
            unset($v['form_wallet_id']);
            unset($v->mem);
            unset($v->member);
            unset($v->wallet);
        }

        return $list;

    }
  


   /**
     * 第三方平台登录接口接口
     */
    public function get_login($data)
    {
        $member=$this->modelMember->getInfo(['username'=>$data['username']],'username,password');
        if(!$member){
            return ajaxreturn(1, lang('用户未注册'));
        }
        if($member['password']!=$data['password']){
            return ajaxreturn(1, lang('密码不正确'));
        }
        return ajaxreturn(0, lang('登录成功'));


    }

    /**
     * 第三方平台交易密码接口
     */
    public function get_trade_pwd($data)
    {


        $member=$this->modelMember->getInfo(['username'=>$data['username']],'username,pin_password');
        if(!$member){
            return ajaxreturn(1, lang('用户未注册'));
        }
       if(!$member['pin_password']){
            return ajaxreturn(1, lang('PIN密码未设置'));
        }
        if($member['pin_password']!=$data['pin_password']){
            return ajaxreturn(1, lang('PIN密码不正确'));
        }
        return ajaxreturn(0, lang('PIN密码正确'));
    }
  
/**
     * 第三方平台提现接口
     */
    public function get_balance($data)
    {
        $arr= ['47.91.255.19','47.106.81.29'];
        if(  !in_array( $_SERVER['REMOTE_ADDR'],$arr)){
            return ajaxreturn(1, lang('您的IP地址不允许访问'));
        }
        $member=$this->modelMember->getInfo(['user_id'=>$data['user_id']]);
        if(!$member){
            return ajaxreturn(1, lang('用户未注册'));
        }
        $account=UserAccount::check(['user_id'=>$member['id'],'wallet_id'=>1]);
        return  $account['balance'] ;


    }



}
